import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import { Form, Table, Card, Button, Divider, Input, DatePicker } from 'antd';
import { utils } from 'vv-frontend-components';
import LinkTo from '@/components/LinkTo';
import { history } from 'umi';
import isEmpty from 'lodash/isEmpty';
// AuthComponent AuthCode权限控制
import AuthCode from '@/utils/auth/AuthCode';
import AuthComponent from '@/utils/auth/AuthComponent';
import authHelpr from '@/utils/auth/helper';
import CompanyDepart from '@/components/CompanyDepart';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import styles from './index.less';

const { RangePicker } = DatePicker;
const Regularization = ({ form, loading, regularization, dispatch, location, route }) => {
    // 按钮权限控制
    const { authCode } = new AuthCode(route.code);
    const { checkCode } = authHelpr;
    // 过滤高级搜索空格
    const { deepTrim } = utils;
    const { query } = location;
    const { pagination, data } = regularization;
    const [showRow, setShowRow] = useState();
    // 获取参数
    const { getFieldsValue } = form;
    const { getFieldDecorator } = form;
    // 获取查询参数
    const getSearchData = pageNo => {
        // 方法自动获取高级搜索表单参数
        const { userName, companyDepart, changeDateSearch } = getFieldsValue();
        // 接口传参参数
        const payload = {
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize,
            // 高级搜索字段
            employeeName: userName || '',
            companyId: companyDepart?.companyId || '',
            departmentId: companyDepart?.departmentId || '',
            startRegularDate:
                !isEmpty(changeDateSearch) && changeDateSearch[0] ? changeDateSearch[0].format('YYYY-MM-DD') : '',
            endRegularDate:
                !isEmpty(changeDateSearch) && changeDateSearch[1] ? changeDateSearch[1].format('YYYY-MM-DD') : ''
        };
        return payload;
    };
    // 接口请求
    const fetchList = (ctx = {}) => {
        const { pageNo = null } = ctx;
        dispatch(
            deepTrim({
                type: 'regularization/fetchList',
                payload: {
                    ...getSearchData(pageNo)
                }
            })
        );
    };

    // 列表项
    const columns = [
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 200,
            render(text, record) {
                return (
                    <LinkTo
                        onClick={async (e, url) => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personnel_management_onboardAndLeave_regularization_detail_click',
                                eventProps: {
                                    label: '转正管理-详情'
                                }
                            });
                            history.push(url);
                        }}
                        style={{
                            display: 'inline-block',
                            maxWidth: 200,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            verticalAlign: ' text-bottom'
                        }}
                        className={styles.employeeName}
                        to="/office/personnelManagement/organization/employeeList/detail"
                        query={{
                            employeeCode: record.employeeCode
                        }}
                    >
                        {text}
                    </LinkTo>
                );
            }
        },
        {
            title: '隶属公司',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 200
        },
        {
            title: '部门',
            dataIndex: 'departmentName',
            key: 'departmentName',
            width: 200,
            render(text, record) {
                return <div>{record.departmentName}</div>;
            }
        },
        {
            title: '职位',
            dataIndex: 'postName',
            key: 'postName',
            width: 200,
            render(text, record) {
                return <div>{record.postName}</div>;
            }
        },
        {
            title: '预计转正日期',
            dataIndex: 'regularDate',
            key: 'regularDate',
            width: 150,
            render(text) {
                return (
                    <div>
                        <span>{moment(text).format('YYYY-MM-DD')}</span>
                        {/* {record.delayRegularDays ? (
                            <div style={{ color: '#f00' }}>已超期限{record.delayRegularDays}天</div>
                        ) : null} */}
                    </div>
                );
            }
        },
        {
            title: '状态',
            dataIndex: 'assigneeEmployeeNames',
            key: 'assigneeEmployeeNames',
            render(text) {
                return <div className={styles.statusDiv}>{text}</div>;
            }
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            fixed: 'right',
            width: 160,
            render(text, record) {
                return (
                    <div>
                        {checkCode(authCode('detail')) ? (
                            <LinkTo
                                onClick={async (e, url) => {
                                    // 埋点
                                    await eventTrack({
                                        eventName: 'personnel_management_onboardAndLeave_regularization_operator_click',
                                        eventProps: {
                                            label: '转正管理-操作-详情'
                                        }
                                    });
                                    history.push(url);
                                }}
                                to="/office/personnelManagement/onboardAndLeave/regularizationDetails"
                                query={{
                                    regularId: record.id,
                                    type: 'company'
                                }}
                            >
                                详情
                            </LinkTo>
                        ) : (
                            <span style={{ color: 'rgba(255,162,45,0.45)' }}>详情</span>
                        )}
                        <AuthComponent code={authCode('history')}>
                            {showRow === record.id && record.finishNum ? <Divider type="vertical" /> : null}
                            {showRow === record.id && record.finishNum ? (
                                <LinkTo
                                    to="/office/personnelManagement/onboardAndLeave/regularHistory"
                                    query={{
                                        employeeCode: record.employeeCode,
                                        employeeName: record.employeeName,
                                        companyId: record.companyId,
                                        type: 'hr'
                                    }}
                                >
                                    历史记录
                                </LinkTo>
                            ) : null}
                        </AuthComponent>
                    </div>
                );
            }
        }
    ];
    const resetForm = () => {
        // 埋点
        eventTrack({
            eventName: 'personnel_management_onboardAndLeave_regularization_reset_click',
            eventProps: {
                label: '入职管理-重置'
            }
        });
        form.resetFields();
        history.push({
            query: {}
        });
    };
    // 分页功能
    const tableChange = paginations => {
        dispatch({
            type: 'regularization/save',
            payload: {
                pagination: {
                    ...regularization.pagination,
                    ...paginations
                }
            }
        });
    };

    // 鼠标移入每一行的事件
    const onRow = row => ({
        onMouseEnter: () => {
            setShowRow(row.id);
        },
        onMouseLeave: () => {
            setShowRow();
        }
    });
    // 每当分页数、页面条数、排序、筛查项改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [pagination.pageSize, pagination.current]);

    useEffect(
        () => () => {
            form.resetFields();
            dispatch({
                type: 'regularization/save',
                payload: {
                    pagination: {
                        pageSize: 10,
                        current: 1,
                        total: 0
                    }
                }
            });
        },
        []
    );

    return (
        <PageHeaderWrapper>
            <Card title="待转正员工" bordered={false}>
                <Form
                    layout="inline"
                    style={{ marginBottom: 12 }}
                    onSubmit={e => {
                        e.preventDefault();
                        fetchList({ pageNo: 1 });
                    }}
                >
                    <Form.Item label="员工姓名">
                        {getFieldDecorator('userName', {
                            initialValue: query.employeeName || ''
                        })(<Input style={{ width: 224 }} placeholder="请输入员工姓名" />)}
                    </Form.Item>
                    <Form.Item label="公司部门">
                        {getFieldDecorator('companyDepart', {
                            initialValue: {
                                companyId: query.companyId,
                                departmentId: query.departmentId
                            }
                            // 按钮权限暂未开发  先写死
                        })(<CompanyDepart />)}
                    </Form.Item>
                    <Form.Item label="转正日期">
                        {getFieldDecorator('changeDateSearch', {
                            initialValue: [
                                query.startRegularDate ? moment(query.startRegularDate) : undefined,
                                query.endRegularDate ? moment(query.endRegularDate) : undefined
                            ]
                        })(<RangePicker format="YYYY-MM-DD" placeholder={['开始日期', '结束日期']} />)}
                    </Form.Item>
                    <Form.Item>
                        <Button
                            type="primary"
                            onClick={() => {
                                // 埋点
                                eventTrack({
                                    eventName: 'personnel_management_onboardAndLeave_regularization_search_click',
                                    eventProps: {
                                        label: '转正管理-查询',
                                        key_words: JSON.stringify(getFieldsValue())
                                    }
                                });
                                history.push({
                                    query: {
                                        ...query,
                                        ...getSearchData()
                                    }
                                });
                                fetchList({ pageNo: 1 });
                            }}
                        >
                            查询
                        </Button>
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType="submit" onClick={resetForm}>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
                <div>
                    <Table
                        bordered={false}
                        columns={columns}
                        loading={loading.models.regularization}
                        scroll={{ x: 'max-content' }}
                        dataSource={data}
                        rowKey="id"
                        onChange={tableChange}
                        onRow={onRow}
                        pagination={false}
                    />
                    <Pagination {...pagination} onChange={tableChange} />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};
export default connect(({ regularization, loading }) => ({
    regularization,
    loading
}))(Form.create()(Regularization));
